<template>
  <div id class="app-container">
    <tab-selector
      v-model="currentTabSelector"
      :options="tabSelectorOptions"
      @tab-change="handleTabChange"
    ></tab-selector>

    <el-form inline label-width="68px">
      <el-form-item label="到店时间">
        <date-picker :value="onClinicTime" @input="handleOnClinicTime" />
      </el-form-item>
      <el-form-item>
        <el-radio-group v-model="timeType" @change="handleTimeType">
          <el-radio-button label="自然时间">自然时间</el-radio-button>
          <el-radio-button label="扎帐时间">扎帐时间</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item label="渠道">
        <el-cascader
          v-model="channel"
          style="width: 260px;"
          :options="channelOptions"
          :props="{ checkStrictly: true }"
          clearable
          @change="handleChannel"
        ></el-cascader>
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-refresh" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb20">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-chat-dot-round"
          :disabled="multiple"
          @click="handleSendMessage"
          >短信</el-button
        >
        <send-message
          v-model="sendMessage.visible"
          :data="sendMessage.data"
        ></send-message>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-full-screen"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <columns-filter-button></columns-filter-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      border
      :data="personList"
      stripe
      :height="clientHeight"
      :max-height="clientHeight"
      @selection-change="handleSelectionChange"
      @row-dblclick="handleDetails"
      @cell-click="handleCellClick"
      @filter-change="handleFilterChange"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        fixed="left"
      ></el-table-column>
      <columns-filter-view>
        <el-table-column
          label="病例号"
          align="center"
          prop="yiyaClinicPerson.caseNumber"
          min-width="150"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view label="头像">
        <el-table-column
          label="头像"
          align="center"
          prop="imageUrl"
          :min-width="'头像'"
        >
          <avatar-image
            slot-scope="scope"
            :patient="scope.row.yiyaClinicPerson"
          ></avatar-image>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="姓名"
          align="center"
          prop="yiyaClinicPerson.name"
          min-width="100"
        >
          <div slot-scope="scope" style="cursor: pointer">
            {{ scope.row.yiyaClinicPerson.name }}
          </div>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column label="手机号" align="center" min-width="180">
          <hover-phone
            slot-scope="scope"
            :type="1"
            :items="scope.row.yiyaClinicPerson"
          />
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="性别"
          align="center"
          prop="yiyaClinicPerson.sex"
        >
          <template slot-scope="scope">{{
            sexEnum[scope.row.yiyaClinicPerson.sex]
          }}</template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="年龄"
          align="center"
          prop="yiyaClinicPerson.age"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="一级渠道"
          align="center"
          prop="yiyaClinicPerson.channelFirst"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="二级渠道"
          align="center"
          prop="yiyaClinicPerson.channelSecond"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="三级渠道"
          align="center"
          prop="yiyaClinicPerson.channelThird"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="客户状态"
          align="center"
          prop="yiyaClinicPerson.personStatus"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="开单状态"
          align="center"
          prop="yiyaClinicPerson.billingStatus"
          column-key="billingStatus"
          :filters="billingStatusOptions"
          min-width="100"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="扫码状态"
          align="center"
          prop="yiyaClinicPerson.scanStatus"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="已交金额"
          align="center"
          prop="yiyaClinicPerson.overMoney"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="欠费"
          align="center"
          prop="yiyaClinicPerson.arrearage"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="TC"
          align="center"
          prop="yiyaAppointment.tcName"
          min-width="100"
          column-key="tcId"
          :filters="tcOptions"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="医生"
          align="center"
          prop="yiyaAppointment.doctorName"
          min-width="100"
          column-key="doctorId"
          :filters="doctorOptions"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="到店时间"
          align="center"
          prop="yiyaAppointment.onClinicTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
              scope.row.yiyaAppointment.onClinicTime &&
              dayjs(scope.row.yiyaAppointment.onClinicTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="初诊时间"
          align="center"
          prop="yiyaClinicPerson.firstDiagnoseTime"
          width="180"
        >
          <template slot-scope="scope">
            {{
              scope.row.yiyaClinicPerson.firstDiagnoseTime &&
              dayjs(scope.row.yiyaClinicPerson.firstDiagnoseTime).format(
                'YYYY-MM-DD HH:mm:ss'
              )
            }}
          </template>
        </el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="黄页编号"
          align="center"
          prop="yiyaClinicPerson.yellowCode"
          :min-width="'到店状态'.length * 30"
        />
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="备注"
          align="center"
          prop="yiyaAppointment.remarks"
          min-width="180"
          :show-overflow-tooltip="true"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="网络咨询师"
          align="center"
          prop="yiyaClinicPerson.networkCounselor"
          min-width="120"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="一级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumFirst"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="二级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumSecond"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <columns-filter-view>
        <el-table-column
          label="三级媒介"
          align="center"
          prop="yiyaClinicPerson.mediumThird"
          :show-overflow-tooltip="true"
          :min-width="'到店状态'.length * 30"
        ></el-table-column>
      </columns-filter-view>
      <empty slot="empty"></empty>
    </el-table>
    <patient-editor-panel
      v-model="patientEditorPanelVisible"
      @submit="getList"
    ></patient-editor-panel>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    ></pagination>

    <user-matcher-result
      contains-temp-clinic-person
      @update="getList"
    ></user-matcher-result>
    <user-matcher-appointment @submit="getList"></user-matcher-appointment>
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { mapState } from 'vuex'
import { exportPerson } from '@/api/services/person'
import { listChannel } from '@/api/erp/channel'
import { listStaff } from '@/api/services/common'
import { allListAppointment } from '@/api/services/appointment'
import { encode, listToTreeOptions } from '@/utils/utils'
import {
  getThisMonthStartWithEnd,
  getThisWeekStartWithEnd,
  getTodayStartWithEnd,
  getTomorrowStartWithEnd,
} from '@/utils/date'
import { sexEnum } from '@/utils/enums'
import { billingStatusOptions, customerStatusOptions } from '@/utils/options'

import {
  ColumnsFilterButton,
  ColumnsFilterView,
} from '@/components/yiya/TableColumnsFilter'
import DatePicker from '@/components/yiya/DatePicker'

const QUERY_PARAMS = {
  pageNum: 1,
  pageSize: 50,
  personStatus: undefined,
  startCreateTime: undefined,
  endCreateTime: undefined,
  startOnClinicTime: undefined,
  endOnClinicTime: undefined,
  channelFirst: undefined,
  channelSecond: undefined,
  channelThird: undefined,

  departments: undefined,
  billingStatus: undefined,
  tcId: undefined,
  doctorId: undefined,
}

const today = getTodayStartWithEnd()
const thisMonth = getThisMonthStartWithEnd()

export default {
  name: 'ShopPatient',
  components: {
    DatePicker,
    ColumnsFilterButton,
    ColumnsFilterView,
    TabSelector: () => import('@/components/yiya/TabSelector'),
    Empty: () => import('@/components/yiya/Empty'),
    HoverPhone: () => import('@/components/yiya/hoverPhone'),
    SendMessage: () => import('@/components/yiya/SendMessage'),
    PatientEditorPanel: () => import('@/components/yiya/PatientEditorPanel'),
    UserMatcherResult: () => import('@/components/yiya/UserMatcherResult'),
    UserMatcherAppointment: () =>
      import('@/components/yiya/UserMatcherAppointment'),
    AvatarImage: () => import('@/components/yiya/avatarImage'),
  },
  data() {
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      personList: [],
      patientEditorPanelVisible: false,
      queryParams: {},
      currentTabSelector: ' ',
      channelList: [],
      channel: [],
      doctorList: [],
      tcList: [],
      timeType: '自然时间',
      onClinicTime: undefined,
      sendMessage: { visible: false, data: [] },
      clientHeight: document.body.clientHeight - 325,
    }
  },
  computed: {
    ...mapState({
      clinicId: (state) => state.clinic.clinicId,
    }),
    dayjs() {
      return dayjs
    },
    sexEnum() {
      return sexEnum
    },
    billingStatusOptions() {
      return billingStatusOptions.map(({ label, value }) => ({
        text: label,
        value,
      }))
    },
    doctorOptions() {
      return this.doctorList.map(({ userName, userId }) => ({
        text: userName,
        value: userId,
      }))
    },
    tcOptions() {
      return this.tcList.map(({ userName, userId }) => ({
        text: userName,
        value: userId,
      }))
    },
    tabSelectorOptions() {
      return [
        {
          label: '总人数',
          value: ' ',
          params: {},
        },
        ...customerStatusOptions.map(({ label, value }) => ({
          label,
          value,
          params: {
            personStatus: value,
          },
        })),
        {
          label: '今日注册',
          value: '今日注册',
          params: {
            startCreateTime: today[0].format('YYYY-MM-DD HH:mm:ss'),
            endCreateTime: today[1].format('YYYY-MM-DD HH:mm:ss'),
          },
        },
        {
          label: '本月注册',
          value: '本月注册',
          params: {
            startCreateTime: thisMonth[0].format('YYYY-MM-DD HH:mm:ss'),
            endCreateTime: thisMonth[1].format('YYYY-MM-DD HH:mm:ss'),
          },
        },
      ]
    },
    channelOptions() {
      return [
        {
          label: '直接上门',
          value: '直接上门',
          children: [
            {
              label: '直接上门',
              value: '直接上门',
              children: [{ label: '直接上门', value: '直接上门' }],
            },
          ],
        },
        ...this.channelList,
      ]
    },
  },
  mounted() {
    this.queryParams = {
      ...QUERY_PARAMS,
      ...this.$route.query,
      clinicId: +this.clinicId,
    }
    this.handleOnClinicTime(getTodayStartWithEnd())
    this.getDoctorList()
    this.getTcList()
    this.getChannelOptions()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        const { rows, total } = await allListAppointment(this.queryParams)
        this.personList = rows
        this.total = total
      } finally {
        this.loading = false
      }
    },
    async getDoctorList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: '医生',
      })

      this.doctorList = data
    },
    async getTcList() {
      const { data } = await listStaff({
        deptId: +this.clinicId,
        postname: 'TC',
      })
      this.tcList = data
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.queryParams.departments = undefined
      this.queryParams.billingStatus = undefined
      this.queryParams.tcId = undefined
      this.queryParams.doctorId = undefined
      const today = getTodayStartWithEnd()
      this.handleOnClinicTime(today)
    },
    handleDetails(row) {
      this.$router.push(
        `/shop/details?id=${row.yiyaClinicPerson.id}&redirect=${encode({
          path: this.$route.path,
          query: this.queryParams,
        })}`
      )
    },
    handleCellClick(row, column) {
      if (column.label === '姓名') {
        this.handleDetails(row)
      }
    },
    handleSelectionChange(selection) {
      this.ids = selection
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    async handleExport() {
      await this.$confirm('是否确认导出所有到店患者信息数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })

      const { msg } = await exportPerson(this.queryParams)

      this.download(msg)
    },
    handleTimeType() {
      let [start, end] = this.onClinicTime
      ;[start, end] = [dayjs(start).startOf('day'), dayjs(end).startOf('day')]
      if (this.timeType === '自然时间') {
        start = start.add(1, 'day')
      }
      this.handleOnClinicTime([start, end])
    },
    handleOnClinicTime([start, end]) {
      ;[start, end] = [dayjs(start).startOf('day'), dayjs(end).startOf('day')]
      if (this.timeType === '自然时间') {
        start = start.startOf(1, 'day')
        end = end.endOf('day')
      } else {
        start = start.subtract(1, 'day').add(16, 'hour')
        end = end.add(16, 'hour')
      }
      this.onClinicTime = [start, end]
      this.queryParams.startOnClinicTime = start.format('YYYY-MM-DD HH:mm:ss')
      this.queryParams.endOnClinicTime = end.format('YYYY-MM-DD HH:mm:ss')
      this.handleQuery()
    },
    handleSendMessage() {
      this.sendMessage = {
        visible: true,
        data: this.ids.map(({ yiyaAppointment, yiyaClinicPerson }) => ({
          id: yiyaClinicPerson.id,
          phoneNumber: yiyaClinicPerson.phoneNumber,
          selectPhoneNumber: [
            {
              phoneNumber: yiyaClinicPerson.phoneNumber,
              phoneOwnership: yiyaClinicPerson.phoneOwnership,
            },
            {
              phoneNumber: yiyaClinicPerson.phoneNumber2,
              phoneOwnership: yiyaClinicPerson.phoneOwnership2,
            },
          ],
          customerName: yiyaClinicPerson.name,
          doctor: yiyaAppointment.doctorName,
          time: yiyaAppointment.reservationDate,
        })),
      }
    },

    handleFilterChange(e) {
      const [key, value] = Object.entries(e)[0]
      this.queryParams[key] = value.join(',')
      this.handleQuery()
    },
    handleTabChange({ params }) {
      this.queryParams.personStatus = params.personStatus
      this.queryParams.startCreateTime = params.startCreateTime
      this.queryParams.endCreateTime = params.endCreateTime
      this.handleQuery()
    },
    async getChannelOptions() {
      const { rows } = await listChannel({
        pageNum: 1,
        pageSize: 10000000,
      })

      this.channelList = listToTreeOptions(rows, ({ pid, id, name }) => ({
        parentId: pid,
        id,
        label: name,
        value: name,
      }))
    },
    handleChannel(e) {
      ;[
        this.queryParams.channelFirst,
        this.queryParams.channelSecond,
        this.queryParams.channelThird,
      ] = e
      this.handleQuery()
    },
  },
}
</script>

